# services/workflow_service.py
from models.workflow import WorkflowInstance, CCRecord, WorkflowStep
from models.user import User
from utils.database import db
from services.notification_service import NotificationService


class WorkflowService:
    @classmethod
    def start_workflow(cls, template_id, form_data, initiator_id):
        instance = WorkflowInstance(
            template_id=template_id,
            form_data=form_data,
            initiator_id=initiator_id
        )
        db.session.add(instance)
        cls._handle_step_cc(template_id, instance, 1)
        db.session.commit()
        return instance

    @classmethod
    def _handle_step_cc(cls, template_id, instance, step_number):
        current_step = WorkflowStep.query.filter_by(
            template_id=template_id,
            step_order=1
        ).first()

        if current_step and current_step.cc_user_ids:
            for user_id in current_step.cc_user_ids:
                db.session.add(CCRecord(
                    instance_id=instance.id,
                    user_id=int(user_id)
                ))
            NotificationService.send_cc_notification(
                instance.id,
                current_step.cc_user_ids
            )
